//
//  AUExtens_Date.swift
//  AwesomeUBaseModule_Example
//
//  Created by Miss_Special on 2018/4/13.
//  Copyright © 2018 CocoaPods. All rights reserved.
//

public extension Date {
    
    static func au_convertDateToString(_ createAt : String, dateFormat: String = "EEE MM dd HH:mm:ss Z yyyy") -> String {
        // 1.创建时间格式化对象
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = dateFormat
        dateFormatter.locale = Locale(identifier: "en")
        
        // 2.将string时间转换为date时间
        guard let createDate = dateFormatter.date(from: createAt) else {
            return ""
        }
        
        // 3.创建当前时间
        let nowDate = Date()
        
        // 4.比较时间
        let timeInterval = Int(nowDate.timeIntervalSince(createDate))
        
        // 刚刚
        if timeInterval < 60 {
            return "刚刚"
        }
        
        // 40分钟前
        if timeInterval < 60 * 60 {
            return "\(timeInterval / 60)分钟前"
        }
        
        // 10小时前
        if timeInterval < 60 * 60 * 24 {
            return "\(timeInterval / (60 * 60))小时前"
        }
        
        // 昨天 10:29
        let calender = Calendar.current
        if calender.isDateInYesterday(createDate) {
            dateFormatter.dateFormat = "HH:mm"
            return "昨天 \(dateFormatter.string(from: createDate))"
        }
        
        // 一年内 : 05-12 10:30
        let components = (calender as NSCalendar).components(NSCalendar.Unit.year, from: createDate, to: nowDate, options: [])
        if components.year! < 1 { // 一年之内
            dateFormatter.dateFormat = "MM-dd HH:mm"
            return dateFormatter.string(from: createDate)
        }
        
        // 一年以上
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
        return dateFormatter.string(from: createDate)
    }
}
